<?php

namespace app\index\controller;

use app\common\api\controller\Error;
use app\common\controller\AliOss;
use app\common\controller\Common;
use app\common\controller\Log;
use app\common\model\BonusRule;
use app\common\model\Channel;
use app\common\api\controller\Relation;
use app\common\api\controller\User;
use app\common\controller\SlideCode as slideCodeObj;

use app\common\model\Levels;
use app\common\model\MemberFinance;
use think\Db;
use think\Exception;
use think\Lang;
use think\Validate;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Home extends Common
{
    private $key;
    protected $uid;
    protected $userInfo;
    protected static $totalList;
    protected $bonusRuleModel;
    private static $access_arr;

    /**
     * 前台控制器初始化
     */
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        self::$totalList = 10;
        $this->key = "hongming";

        $this->bonusRuleModel = BonusRule::find();
        self::$access_arr = ['User/index', 'Index/uploadImg', 'User/authapply', 'User/userauthpay'];
    }

    /**
     * 登录验证(只有登录的会员才有信息输出)
     */
    protected function check_load()
    {
        $token = input('token');
        if (!$token) {
            $this->apiError('关键参数缺失！');
        }
        $data = $this->parseToken($token);

        if ($data['status'] != 200) {
            $this->apiError('登录信息已过期！', -10, '/pages/login/login');
        }

        $this->uid = $data['data']["uid"];
        $userinfo = Db('member')->where('uid', $this->uid)->find();

        $controller = request()->controller();
        $action = request()->action();
        $route = $controller . '/' . $action;
//        Log::insertLog($route);
//        Log::insertLog(self::$access_arr);
        if (!in_array($route, self::$access_arr)) {
            if ($userinfo['status'] == 1) {
                $this->apiError('请先完成实名认证！', -20, '/pages/user/user-auth');
            }

            if ($userinfo['status'] == 2) {
                $this->apiError('实名认证正在审核中，暂不可进行该操作！', -30, '/pages/user/user-auth');
            }
        }

        $userrank_name = Levels::where('id', $userinfo['userrank'])->value('name');
        $userinfo['userrank_name'] = $userrank_name;
        $userfinance = Db('member_finance')->where('uid', $this->uid)->find();
        if (!$userfinance) {
            $userfinance = [];
        }

        $tInfo = \app\common\model\Traders::where('uid', $this->uid)->where('status', 1)->find();
        if ($tInfo->id) {
            $userinfo['is_trader'] = true;
            $userinfo['trader_money'] = $tInfo->hasmoney;
        } else {
            $userinfo['is_trader'] = false;
            $userinfo['trader_money'] = 0.00;
        }

        $this->userInfo = array_merge($userinfo, $userfinance);
    }

    /**
     * 会员注册
     */
    public function registerIndex()
    {
        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }

        $rules = [
            'mobile' => 'require|length:11',
            'code' => 'require',
//            'tuijiannumber' => 'require',
            'password' => 'require|min:6',
            'password2' => 'require|min:6',
        ];
        $messages = [
            'mobile.require' => '手机号码必填',
            'mobile.length' => '手机号码为11位',
            'code.require' => '短信验证码必填',
//            'tuijiannumber.require' => '推荐人账号必填',
            'password.require' => '登录密码必填',
            'password.min' => '登录密码不能少于6位数',
            'password2.require' => '支付密码必填',
            'password2.min' => '支付密码不能少于6位数'
        ];

        $data = input();

        $validate = new Validate($rules, $messages);
        $result = $validate->check($data);

        if (!$result) {
            $this->apiError($validate->getError());
        }

        $res = $this->checkCode($data['mobile'], $data['code']);
        if ($res['status'] == 0) {
            $this->apiError($res['msg']);
        }

        if ($data['tuijiannumber']) {
            $tusernumber = Db('member')->where('usernumber', $data['tuijiannumber'])->value('usernumber');
            if (!$tusernumber) {
                $this->apiError('推荐人不存在！');
            }
        } else {
            $tusernumber = Db('member')->order('uid asc')->value('usernumber');
        }

        $relationApi = new Relation();
        $tdata = $relationApi->tRelation($tusernumber);

        //注册成功
        $userdata = array(
            'usernumber' => $data['mobile'],
            'mobile' => $data['mobile'],
            'psd1' => $data['password'],
            'psd2' => $data['password2'],
        );

        /*判断是否存在推荐关系*/
        if (isset($tdata)) {
            if ($tdata['code'] > 0) {
                unset($tdata['code']);
                $userdata = array_merge($userdata, $tdata);
            } else {
                $this->apiError(Error::regError($tdata['code']));
            }
        }

        $UserApi = new User();
        $res = $UserApi->register($userdata);
        if ($res['status'] == 0) {
            $this->apiError($res['msg']);
        }

        $this->destroyCode($data['mobile']);
        $token = $this->makeToken($res['data']);
        $this->apiSuccess($res['msg'], ['token' => $token]);
    }

    /**
     * 生成签名
     * @param $uid
     * @return string
     */
    protected function makeToken($uid)
    {
        $time = time();
        $data = array(
            "iss" => "",
            "aud" => "",
            'iat' => $time, //签发时间
            'nbf' => $time + 1, //在什么时间之后该jwt才可用
            'exp' => $time + 604800, //过期时间
            "uid" => $uid
        );
        $token = JWT::encode($data, $this->key, 'HS256');
        return $token;
    }

    /**
     * 解析token
     * @param $token
     * @return mixed
     */
    protected function parseToken($token)
    {
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, new Key("hongming", "HS256"));
            $arr = (array)$decoded;
            return ['status' => 200, 'data' => $arr];
        } catch (\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            return ['status' => -101, 'msg' => $e->getMessage()];
        } catch (\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return ['status' => -102, 'msg' => $e->getMessage()];
        } catch (\Firebase\JWT\ExpiredException $e) {  // token过期
            return ['status' => -103, 'msg' => $e->getMessage()];
        } catch (Exception $e) {  //其他错误
            return ['status' => -104, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 上传图片
     * @author huajie <banhuajie@163.com>
     */
    public function uploadImg()
    {
        if (request()->isPost()) {
            $file = isset($_FILES['download']) ? $_FILES['download'] : $_FILES['file'];
            $res = AliOss::uploadFile('pics', $file);
            return json_encode($res);
        }
    }

    /**
     * 关于滑动验证码
     */
    public function slideCode()
    {
        $res = slideCodeObj::index();
        if ($res['code'] == 0) {
            $this->apiError($res['msg']);
        }

        $this->apiSuccess($res['msg'], ['data' => $res['data']]);
    }
}